package com.jddup.program.etm.postgresql;

import com.jddup.common.annotations.ColumnDes;
import com.jddup.common.pojo.TableColumn;
import com.jddup.program.etm.TableColumnColumnDesConvertor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;

/**
 * Created by ZZB on 2017/12/4.
 */
public class PostgresqlTableColumnColumnDesConvertor implements TableColumnColumnDesConvertor {
    private static final Logger logger = LoggerFactory.getLogger(PostgresqlTableColumnColumnDesConvertor.class);
    @Override
    public void convertFromColumnDes(String tableName ,TableColumn tableColumn, ColumnDes columnDes) {
        Class clazz = tableColumn.getPropertyType();
        if(clazz.equals(String.class)){
            if(columnDes.maxLength() <= 255) {
                tableColumn.setColumnType("VARCHAR");
            } else {
                tableColumn.setColumnType("TEXT");
            }
        } else if (clazz.equals(Integer.class) || clazz.equals(int.class)){
            BigInteger bigInteger = new BigInteger(columnDes.maximum());
            if(bigInteger.compareTo(BigInteger.valueOf(32767)) <= 0){
                tableColumn.setColumnType("INT2");
            } else {
                tableColumn.setColumnType("INT4");
            }
        }
        setCommonPropertiesInTableColumn(tableColumn,columnDes);
        if(!tableColumn.getSigned() ){
            logger.error("postgreSQL not support unsign ! tableName [{}], column [{}]",tableName,tableColumn.getColumnName());
            tableColumn.setSigned(true);
        }
    }
}
